from flask import request, g

from app.libs.error_code import Success
from app.libs.redprint import Redprint
from app.libs.token_auth import login_required
from app.models.case import CaseModel
from app.validates.case import CaseForm, UpdateCaseForm

api = Redprint('case')


@api.route('', methods=['GET'])
@login_required
def get_case():
    form = CaseForm().validate_and_api()
    cases = CaseModel.get_case(form.id.data)
    return Success(data=cases)


@api.route('', methods=['PUT'])
@login_required
def update_case():
    forms = request.json
    case_list = []
    for form_data in forms:
        form = UpdateCaseForm(re_data=form_data).validate_and_api()
        case_list.append({
            "name": form.name.data,
            "method": form.method.data,
            "url": form.url.data,
            "execution_order": forms.index(form_data),
            "group_id": form.group_id.data,
            "headers": form.headers.data if form.headers.data else '',
            "body": form.body.data if form.body.data else '',
            "params": form.params.data if form.params.data else '',
            "id": form.id.data,
            "condition": form.condition.data if form.condition.data else '',
            "update_user": g.user,
            "create_user": g.user
        })
    CaseModel.update_add_case(case_list)
    return Success()
